package com.mfcxy.exception;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mfcxy.tools.BackJson;


public class CustomExceptionResolver implements HandlerExceptionResolver  {

	// 前端控制器DispatcherServlet在进行HandlerMapping、调用HandlerAdapter执行Handler过程中，如果遇到异常就会执行此方法
		// handler最终要执行的Handler，它的真实身份是HandlerMethod
		// Exception ex就是接收到异常信息
		@Override
		public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
				Exception ex) {

			ModelAndView mv = new ModelAndView();
			// 输出异常
			ex.printStackTrace();

			// 统一异常处理代码
			// 针对系统自定义的CustomException异常，就可以直接从异常类中获取异常信息，将异常处理在错误页面展示
			// 异常信息
			String message = null;
			CustomException customException = null;

			if (ex instanceof CustomException) { // 如果是自定义异常
				customException = (CustomException) ex;
				message = customException.getMessage();
			} else {
				// 针对非CustomException异常.
				message = "页面错误请稍后再试。。。";
			}

			request.setAttribute("message", message);
			
			// 如果是ajax 请求
			String requestType = request.getHeader("X-Requested-With");
			if (requestType != null && requestType.equals("XMLHttpRequest")) {
				response.setCharacterEncoding("UTF-8");
				response.setContentType("application/json; charset=utf-8");
				ObjectMapper mapper = new ObjectMapper();
				BackJson bj = new BackJson();
				bj.setCode(0);
				bj.setMsg(message);
				try {
					//把BackJson 转换成json对象
					mapper.writeValue(response.getWriter(), bj);
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				// 转向到错误 页面
				mv.addObject("message", message);
				mv.setViewName("admin/message");
			}

			return mv;
		}

}
